package org.csu.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class ProviderController {

    //SPEL
    @Value("${server.port}")
    private String port;

    /**
     * 验证码工具
     */
    @Autowired
    DefaultKaptcha defaultKaptcha;

    /**
     * redis工具
     */
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/index")
    public String index() {
        return this.port;
    }

    @GetMapping("/img")
    @ResponseBody
    public Map img(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            String createText = defaultKaptcha.createText();
            // 生产验证码字符串并保存到 Redis 中，ip-rightCode，有效期为 1 小时
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token, createText, 1, TimeUnit.HOURS);
            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
            String base64bytes = Base64.encode(jpegOutputStream.toByteArray());

            //该字符串传输至前端放入src即可显示图片，安卓可以去掉data:image/png;base64,
            String src = "data:image/jpg;base64," + base64bytes;
            Map<String, Object> map = new HashMap<>(2);
            map.put("token", token);
            map.put("img", src);
            return map;
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return null;
        }

    }
}
